package com.atguigu.msmservice.controller;

import com.atguigu.commonutils.R;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.RandomUtil;
import com.mysql.cj.util.StringUtils;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @Author: shaki
 * @Date: 2021/6/22 10:48
 */
@RestController
@RequestMapping("/edumsm/msm")
public class MsmController {
    @Resource
    private MsmService msmService;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    //发送邮件
    @GetMapping("send/{email}")
    public R sendMsm(@PathVariable("email") String email){
        //从redis获取验证码，获取到直接返回，获取不到，邮件发送
        String code = redisTemplate.opsForValue().get(email);
        if(!StringUtils.isNullOrEmpty(code)){
            return R.ok().data("code",code);
        }
        //获取不到，邮件发送
        code = RandomUtil.getFourBitRandom();
        boolean isSend = msmService.send(code,email);
        if(isSend){
            redisTemplate.opsForValue().set(email,code,5, TimeUnit.MINUTES);
            return R.ok().data("code",code);
        }else{
            return R.error().message("邮件发送失败");
        }

    }
}
